﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Microsoft.SharePoint;

namespace SlamCms.SharePoint.Migration
{
	public class MigratableField : IMigratable
	{
		#region Properties
		public string Title { get; set; }
		public string StaticName { get; set; }
		public string Group { get; set; }
		public string SchemaXml { get; set; }
		public string Source { get; set; }
		public string LookupList { get; set; }

		#endregion

		public bool Equals(SPField field)
		{
			XElement migrateFieldSchema = XElement.Parse(SchemaXml);
			XElement fieldSchema = XElement.Parse(field.SchemaXml);

			migrateFieldSchema.Attribute("ID").Remove();
			migrateFieldSchema.Attribute("SourceID").Remove();
			fieldSchema.Attribute("ID").Remove();
			fieldSchema.Attribute("SourceID").Remove();
			if (migrateFieldSchema.Attribute("Version") != null)
				migrateFieldSchema.Attribute("Version").Remove();
			if (fieldSchema.Attribute("Version") != null)
				fieldSchema.Attribute("Version").Remove();

			return XNode.DeepEquals(migrateFieldSchema, fieldSchema);
		}

		#region Serlialization

		public XElement ToXml()
		{
			XElement node = new XElement("Field");
			node.Add(new XAttribute("Title", Title));
			node.Add(new XAttribute("StaticName", StaticName));
			node.Add(new XAttribute("Group", Group));
			node.Add(new XAttribute("Source", Source));
			node.Add(new XAttribute("SchemaXml", !String.IsNullOrEmpty(SchemaXml) ? System.Web.HttpUtility.HtmlEncode(SchemaXml) : String.Empty));
			if (!String.IsNullOrEmpty(LookupList))
				node.Add(new XAttribute("LookupList", LookupList));
			return node;
		}

		public void FromXml(XElement element)
		{
			this.Title = element.Attribute("Title").Value;
			this.StaticName = element.Attribute("StaticName").Value;
			this.Group = element.Attribute("Group").Value;
			this.Source = element.Attribute("Source").Value;
			if (element.Attribute("LookupList") != null)
				this.LookupList = element.Attribute("LookupList").Value;
			this.SchemaXml = System.Web.HttpUtility.HtmlDecode(element.Attribute("SchemaXml").Value);
		}
		
		#endregion
	}
}
